import React, { useEffect, useState } from "react";
import { message, Upload } from "antd";
import { stati } from "../../api/api";
import { deldetailimg } from "../../api/serve";
import ImgCrop from "antd-img-crop";
import api from "../../api/api";
//文件上传的组件
const Uploadimg = ({ setImglist, Imglist }) => {
  const [fileList, setFileList] = useState([]);
  useEffect(
    function () {
      //父组件的imglist里面的内容影响子组件里面的内容
      if (Imglist) {
        let arr = Imglist.split(",").map((item) => ({
          url: stati + item,
          name: item,
          status: "done",
          uid: item,
        }));
        setFileList(arr);
      } else {
        setFileList([]);
      }
    },
    [Imglist]
  );
  const onChange = ({ file, fileList: newFileList, event }) => {
    // change事件只要文件有变化就会触发change事件
    if (file.response && file.response.success) {
      // 判断条件符合这个条件就将file的数据进行拼接 服务器地址
      if (newFileList.length !== 0) {
        const { url } = file.response.data;
        newFileList.at(-1).url = stati + url;
        // 给newFileList添加更改后的数据方便后续对图片进行删除
        newFileList.at(-1).name = url;
        setImglist(newFileList.map((item) => item.name).join(","));
      }
    }
    console.log(file, newFileList, event);
    setFileList(newFileList);
    // 将newFileList里面的图片路径传递给父组件里面 用join返回成字符串
  };
  // 图片预览
  const onPreview = async (file) => {
    let src = file.url;
    if (!src) {
      src = await new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file.originFileObj);
        reader.onload = () => resolve(reader.result);
      });
    }
    const image = new Image();
    image.src = src;
    const imgWindow = window.open(src);
    imgWindow?.document.write(image.outerHTML);
  };
  const handleRemove = (file) => {
    const { name } = file;
    // 进行图片的删除
    if (fileList.length === 1) {
      setFileList([]);
    }
    deldetailimg({ file: [name] }, (res) => {
      message.success("删除成功");
    });
  };

  return (
    <ImgCrop rotate>
      <Upload
        action={api.adddetailimg}
        listType="picture-card"
        fileList={fileList}
        onChange={onChange}
        onPreview={onPreview}
        onRemove={handleRemove}
      >
        {fileList.length < 5 && "+ Upload"}
      </Upload>
    </ImgCrop>
  );
};
export default Uploadimg;
